package com.cheval.rpcframe.protocal;

import com.cheval.rpcframe.common.Invocation;
import com.cheval.rpcframe.common.Message;
import com.cheval.rpcframe.common.MessageType;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyFactory {

    public static <T> T getProxy(Class<T> interfaceClass) {
        Object proxy = Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Invocation invocation = new Invocation(interfaceClass.getSimpleName(), method.getName(), method.getParameterTypes(), args);
                Message message = new Message();
                message.setMessageType(MessageType.INVOKE);
                message.setInvocation(invocation);

                ConsumerClient consumerClient = new ConsumerClient();
                Object res = consumerClient.removeInvoke("localhost", 8080, message);
                return res;
            }
        });
        return (T) proxy;
    }

    public static <T> T getProxy(Class<T> interfaceClass, String version) {
        Object proxy = Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Invocation invocation = new Invocation(interfaceClass.getSimpleName(), method.getName(), method.getParameterTypes(), args, version);
                Message message = new Message();
                message.setMessageType(MessageType.INVOKE);
                message.setInvocation(invocation);

                ConsumerClient consumerClient = new ConsumerClient();
                Object res = consumerClient.removeInvoke("localhost", 8080, message);
                return res;
            }
        });
        return (T) proxy;
    }
}
